<?php

// @formatter:off
/**
 * @file WCServicesManager.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: WCServicesManager.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/includes/services/WCServicesManager.php $
 */
// @formatter:on

/**
 * @class WCServicesManager
 */
class WCServicesManager extends WCSingleton {
	//
	// Public properties.
	protected $_explanations = array(
		"class" => false,
		"paths" => array()
	);
	//
	// Public methods.
	/**
	 * @return WCService
	 */
	public function currentService() {
		$out = false;

		if(isset($_REQUEST[WC_URLPARAM_SERVICE])) {
			$service = explode(":", str_replace(array(":", "/"), ":", $_REQUEST[WC_URLPARAM_SERVICE]));

			$filename = $this->guessFilename($service);
			if($filename) {
				require_once $filename;
			}

			$class = $this->guessClass($service);

			if($class) {
				$out = new $class();
			}
		}

		return $out;
	}
	public function promptSearch() {
		echo json_encode($this->_explanations);
	}
	//
	// Protected methods.
	protected function genFilenames($service) {
		$out = array();

		$count = count($service);
		if($count > 1) {
			$item = array_shift($service);

			foreach($this->genFilenames($service) as $geItem) {
				$out[] = "{$item}/{$geItem}";
				$out[] = "{$item}_{$geItem}";
				$out[] = "{$item}-{$geItem}";
			}
		} elseif($count == 1) {
			$out[] = $service[0];
		}

		return $out;
	}
	protected function guessClass($service) {
		$class = "WCService".str_replace(" ", "", ucwords(implode(" ", $service)));

		$this->_explanations["class"] = array(
			"name" => $class,
			"found" => true
		);

		if(!class_exists($class)) {
			$class = false;
			$this->_explanations["class"]["found"] = false;
		}

		return $class;
	}
	protected function guessFilename($service) {
		global $wcServicesDefaults;
		global $wcROOTDIR;

		$guessList = $this->genFilenames($service);

		$filename = false;
		$found = false;
		foreach($wcServicesDefaults["paths"] as $path) {
			foreach($guessList as $genItem) {
				$filename = WCSanitizer::SystemPath("{$wcROOTDIR}/{$path}/{$genItem}.php");

				$explain = array(
					"filename" => $filename,
					"found" => is_readable($filename)
				);
				$this->_explanations["paths"][] = $explain;

				if($explain["found"]) {
					$found = true;
					break;
				} else {
					$filename = false;
				}
			}

			if($found) {
				break;
			}
		}

		return $filename;
	}
}
